Skip to content

feat: disable webhook v1 by default and add startup Quartz migration job - #4066

Open
alfespa17 wants to merge 2 commits into
feat/webhook-v1-disable-flagfrom
feat/webhook-v1-to-v2-startup-migration
Open

alfespa17 wants to merge 2 commits into
feat/webhook-v1-disable-flagfrom
feat/webhook-v1-to-v2-startup-migration

Conversation

@alfespa17

@alfespa17 alfespa17 commented Nov 29, 2026 •

Copy link
Copy Markdown
Member

Summary

Phase 3 of the stacked PR plan to deprecate Webhook v1 and standardize on shared repository webhooks (Webhook v2): flips io.terrakube.webhook.v1.disabled to true by default and introduces a cluster-safe, @DisallowConcurrentExecution startup Quartz job that sequentially migrates any remaining unmigrated v1 workspaces to v2.

Stack Overview

PR Branch Base Scope Status
#4064 feat/webhook-v2-bitbucket main Bitbucket Webhook v2 support (API + UI) Open
#4065 feat/webhook-v1-disable-flag feat/webhook-v2-bitbucket io.terrakube.webhook.v1.disabled flag, 404/hook enforcement, UI v2-only creation Open
#4066 (This PR) feat/webhook-v1-to-v2-startup-migration feat/webhook-v1-disable-flag Startup @DisallowConcurrentExecution Quartz migration job + default disabled=true Open

Changes

  • Configuration Defaults (application.properties, WebhookProperties, application-test.properties):
    • Set io.terrakube.webhook.v1.disabled=${WebhookV1Disabled:true} (default true).
    • Added io.terrakube.webhook.v1.migration-on-startup=${WebhookV1MigrationOnStartup:true} (disabled in application-test.properties so unrelated H2 test fixtures are not modified on context start).
  • Repository Query (WebhookRepository):
    • Added findUnmigratedV1Webhooks(Set<VcsType>) fetching live workspaces with migratedV2 = false.
  • Startup Quartz Migration (WebhookV1ToV2MigrationScheduler, WebhookV1ToV2MigrationJob, WebhookV1ToV2MigrationService, WebhookV1ToV2MigrationTransactions):
    • Scheduled once on ApplicationReadyEvent when v1.disabled=true and migrationOnStartup=true using a deterministic JobKey that coalesces across API replicas.
    • Annotated WebhookV1ToV2MigrationJob with @DisallowConcurrentExecution.
    • Sequentially migrates unmigrated webhooks one by one across GITHUB, GITLAB, AZURE_DEVOPS, AZURE_SP_MI, and BITBUCKET: deletes the legacy v1 remote hook outside DB transactions (tolerating 404), marks migratedV2 = true in an independent REQUIRES_NEW transaction, and schedules RepoWebhookSyncScheduler.scheduleSync(...). Subsequent API restarts find 0 unmigrated webhooks and exit cleanly.
  • Tests:
    • Added WebhookV1ToV2MigrationServiceTest, WebhookV1ToV2MigrationJobTest, and WebhookV1ToV2MigrationSchedulerTest.
    • Updated WebhookV1DisabledIntegrationTest to assert default 404 behavior without property overrides, and updated legacy v1 tests (WebhookV1MigratedSecurityIntegrationTest, WebhookTests, WebhookManageHookTest, WebHookControllerTest).

Verification

  • API unit tests (WebhookV1ToV2Migration*Test, WebHookControllerTest, WebhookManageHookTest, WebhookEventManageHookTest, WebhookServiceTest, RepoWebhookServiceTest, BitBucketWebhookServiceTest, WebhookSecurityHardeningTest, ModuleManageHookTest): 167 tests passed (0 failures, 0 errors).
  • API integration tests (WebhookV1DisabledIntegrationTest, WebhookV1MigratedSecurityIntegrationTest, WebhookTests, CanonicalPathAliasSecurityTests, RepoWebhookJobAuditIntegrationTest, ModuleRefreshTransactionsIntegrationTest): 63 tests passed (0 failures, 0 errors).
  • UI tests & checks (Webhook.test.tsx: 27/27 passed; lint:check: 0 errors; format:check & typecheck: passed).

@Macbet Macbet left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Quartz side looks right: the job store is clustered JDBC, the fixed JobKey prevents concurrent runs across replicas, HTTP calls are outside transactions, and markMigrated re-reads the row. My concern is the upgrade path for installations with existing v1 webhooks: there are several ways a workspace ends up with no working webhook and nothing retries it. Details inline.


if (webhook.getRemoteHookId() != null && !webhook.getRemoteHookId().isBlank()) {
try {
deleteLegacyV1Hook(workspace, vcs.getVcsType(), webhook.getRemoteHookId());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The order here is delete v1 hook -> mark migratedV2 -> schedule async v2 sync, and /webhook/v1/{id} already returns 404 for every row from startup. That leaves a few holes on upgrade:

  • Deliveries are lost for each workspace until its turn in this sequential loop plus the async RepoWebhookSyncJob.
  • If the v2 sync fails afterwards (expired token, missing hook permission, rate limit), the row is already migratedV2=true, so findUnmigratedV1Webhooks never returns it again and the sync is not retried. The workspace has no webhook until someone re-saves its settings.
  • If this delete fails with anything other than 404, the row stays v1 while the endpoint is dead, and the only retry is the next restart. A transient 5xx on cleaning up an already useless hook blocks the v2 setup.

Suggestion: keep serving v1 for rows that are still migratedV2=false (WebhookService already ignores v1 deliveries for migrated rows), create the v2 hook first, delete the v1 hook only after the sync succeeded as best-effort cleanup, and periodically retry rows that have syncError set.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 491a78d: WebhookV1ToV2MigrationService now marks webhooks migratedV2 = true and schedules shared v2 sync (repoWebhookSyncScheduler.scheduleSync) before attempting best-effort legacy v1 hook deletion, so a failing v1 delete no longer blocks v2 migration. Added WebhookRepository.findMigratedWebhooksNeedingRetry so subsequent startups automatically retry shared v2 sync when syncError != null and retry v1 hook deletion when remoteHookId is still populated.

boolean marked = transactions.markMigrated(webhook.getId());
if (marked) {
String workspaceId = workspace.getId() != null ? workspace.getId().toString() : null;
repoWebhookSyncScheduler.scheduleSync(normalizedUrl, workspaceId);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Possible race for repos shared by several workspaces (I have not reproduced it): scheduleSync coalesces by repository URL. Workspace A is marked and its sync job starts right away; workspace B on the same repo is marked a moment later and its scheduleSync hits ObjectAlreadyExistsException because A's job detail still exists. If A's job already ran its findByNormalizedSourceWithMigratedWebhook query before B was marked, B's event types never get subscribed on the shared hook.

Grouping by normalized URL, marking all rows of a repo first and scheduling one sync per URL after that would avoid it, and also cuts the number of sync jobs on large installs.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 491a78d: unmigrated webhooks are now grouped by RepoUrlNormalizer.normalize(workspace.getSource()), and every valid webhook in the repository group is committed as migratedV2 = true before scheduling a single repoWebhookSyncScheduler.scheduleSync(normalizedUrl, seedWorkspaceId) call for that repository.

return false;
}
webhook.setMigratedV2(true);
webhook.setRemoteHookId(null);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some provider delete failures never reach the catch in the service: AzDevOpsWebhookService.callAzureApi catches RestClientException and returns null, the GitHub client returns null when it cannot get a token, and GitLab's deleteWebhook catches IOException. In those cases we still get here and drop remoteHookId, so the orphan v1 hook stays at the provider and the id needed to clean it up later is gone. Could the delete report success, and the id be cleared only when deletion is confirmed (or 404)?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 491a78d: updated deleteWebhook(Workspace, String) across GitHub, GitLab, Azure DevOps, and Bitbucket webhook services to return boolean (true only on 2xx or 404). markMigrated now preserves remoteHookId, and clearRemoteHookId is called in its own transaction only after deletion is confirmed true.

}

@Transactional(propagation = Propagation.REQUIRES_NEW)
public void recordMigrationError(UUID webhookId, String error) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The error recorded here is hard to notice: the UI only renders syncError when migratedV2 is true, and these rows are by definition not migrated. The job summary is also logged at INFO only, a WARN when failed > 0 would help operators.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 491a78d:

  • Updated Webhook.tsx so the syncError warning banner renders whenever webhookEnabled && webhookId && syncError (regardless of migratedV2), and added a corresponding assertion in Webhook.test.tsx.
  • Updated WebhookV1ToV2MigrationService and WebhookV1ToV2MigrationJob to log at WARN when summary.failed() > 0.

# When true (default), the legacy per-workspace /webhook/v1/{webhookId} endpoint returns 404,
# new webhooks for supported VCS providers are always created as shared v2 webhooks, and a
# startup Quartz job migrates any remaining unmigrated v1 workspaces to v2 one by one.
io.terrakube.webhook.v1.disabled=${WebhookV1Disabled:true}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this flips a default on upgrade, could we document both properties (docs / release notes), including that WebhookV1Disabled=false is the opt-out and that it also skips the migration?

Also disabled=true with migration-on-startup=false is accepted and silently leaves every unmigrated workspace with a 404 endpoint and no migration. A startup WARN with the count of unmigrated rows in that combination would make it visible.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 491a78d: documented WebhookV1Disabled=false as the opt-out in application.properties, and updated WebhookV1ToV2MigrationScheduler to query countUnmigratedV1Webhooks and log a WARN with the remaining count when io.terrakube.webhook.v1.disabled=true and io.terrakube.webhook.v1.migration-on-startup=false.

@alfespa17
alfespa17 force-pushed the feat/webhook-v1-to-v2-startup-migration branch from 5146100 to 491a78d Compare November 30, 2026 14:52
@sonarqubecloud

Copy link
Copy Markdown

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/scheduler Touches job scheduling, queueing or locking author/maintainer Authored by a maintainer priority/high Review soon: high-risk area, bug fix or security update size/L 250-999 lines changed terrakube-api terrakube-ui type/feature New functionality

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants